# -*- coding: utf-8 -*-

from odoo import models, fields, api,_
from odoo.tools import float_compare, get_lang
from odoo.exceptions import UserError, ValidationError


class SaleOrder(models.Model):
    _name = 'sale.order'
    _inherit = ['sale.order', 'base.approve']
    approval_record_ids = fields.One2many('approval.records', 'res_id',
                                          domain=[('res_model', '=', 'sale.order')])
    approve_flow_ids = fields.One2many('approve.flow', 'res_id', domain=[('res_model', '=', 'sale.order')])
    # customer_order_name=fields.Char(string=u'客户订单')
    shipping_date=fields.Date(compute='compute_shipping_info')
    shipping_no=fields.Date(compute='compute_shipping_info')


    def compute_shipping_info(self):
        for r in self:
            if r.picking_ids:
                r.shipping_date=r.picking_ids[0].date
                r.shipping_no=r.picking_ids[0].display_name

    state = fields.Selection([
        ('draft', 'Quotation'),
        ('to approve', '待簽核'),
        ('approve', '簽核完成'),
        ('sent', 'Quotation Sent'),
        ('sale', 'Sales Order'),
        ('rejected', '拒绝'),
        ('done', 'Locked'),
        ('cancel', 'Cancelled'),
    ], string='状态', readonly=True, copy=False, index=True, track_visibility='onchange', default='draft')

    def get_default_department_id(self):
        if self.env.user.employee_ids:
            return self.env.user.employee_ids[0].department_id.id

    department_id = fields.Many2one('hr.department', ondelete='restrict', string='部门',
                                    default=get_default_department_id)
    def check_values(self):
        if not self.order_line:
            raise UserError('请添加明细行')
        self.order_line.validate_the_price_unit()
        super(SaleOrder, self).check_values()

    def action_approve_done(self, remark=''):
        super(SaleOrder, self).action_approve_done()
        if remark:
            reject_str = "備註：" + remark
            self.message_post(reject_str)
        self.action_confirm()
    def set_to_done(self):
        self.state = 'sale'


class SaleOrderLine(models.Model):
    _inherit = 'sale.order.line'

    """
    订单号    订单日期   客户名称    业务员 料号  品名 规格  单位  订单数量   出货数量  已交数量  币别  税率   未税单价    订单金额   客户料号  客户订单号   付款条款 																	

    """


    customer_pn=fields.Char(string=u'客户料号')
    customer_order_name=fields.Char(string=u'客户订单号')

    description=fields.Char(string=u'规格')
    @api.onchange('product_id')
    def onchange_product_id_for_des(self):
        if not self.product_id:
            self.description=''
        else:
            code = self.env['product.partner.code'].search(
                [('partner_id', '=', self.order_partner_id.id), ('product_tmpl_id', '=', self.product_id.product_tmpl_id.id)],
                limit=1)
            if code:
                self.customer_pn=code[0].code
            else:
                self.customer_pn=''
            self.description=self.product_id.description
    # @api.depends('order_partner_id','product_id')
    # def compute_customer_pn(self):
    #     for r in self:
    #         customer=self.env['product.partner.code'].search([('partner_id','=',r.order_id.partner_id.id),('product_tmpl_id','=',r.product_id.product_tmpl_id.id)])
    #         if customer:
    #             r.customer_pn=customer[0].code
    #         else:
    #             r.customer_pn = ''
    def get_the_price(self):
        line_id=self.env['sale.pricing.order.line'].search([('product_id','=',self.product_id.id),('partner_id','=',self.order_partner_id.id),('state','=','done')],order='new_date desc',limit=1)

        if line_id:
            return line_id.price_unit
        else:
            raise UserError('未找到对应核价单')


    state = fields.Selection([
        ('draft', 'Quotation'),
        ('to approve', '待簽核'),
        ('approve', '簽核完成'),
        ('sent', 'Quotation Sent'),
        ('sale', 'Sales Order'),
        ('rejected', '拒絕'),
        ('done', 'Locked'),
        ('cancel', 'Cancelled'),
    ], string='状态', related='order_id.state',store=True)

    def validate_the_price_unit(self):
        for r in self:
            if r.get_the_price():
                if float_compare(r.get_the_price(),r.price_unit,precision_digits=2)!=0:
                    raise UserError('与核价单价格不一致，请核对')

    @api.constrains('tax_id')
    def _check_tax_id(self):
        if self.tax_id and len(self.tax_id)>1:
            raise ValidationError(_('税率不能超过1个'))


    @api.onchange('product_id','partner_id')
    def product_id_change(self):
        if not self.product_id:
            return
        if self.order_id.partner_id.tax_id:
            self.tax_id = self.order_id.partner_id.tax_id
        valid_values = self.product_id.product_tmpl_id.valid_product_template_attribute_line_ids.product_template_value_ids
        # remove the is_custom values that don't belong to this template
        for pacv in self.product_custom_attribute_value_ids:
            if pacv.custom_product_template_attribute_value_id not in valid_values:
                self.product_custom_attribute_value_ids -= pacv

        # remove the no_variant attributes that don't belong to this template
        for ptav in self.product_no_variant_attribute_value_ids:
            if ptav._origin not in valid_values:
                self.product_no_variant_attribute_value_ids -= ptav

        vals = {}
        if not self.product_uom or (self.product_id.uom_id.id != self.product_uom.id):
            vals['product_uom'] = self.product_id.uom_id
            vals['product_uom_qty'] = self.product_uom_qty or 1.0

        product = self.product_id.with_context(
            lang=get_lang(self.env, self.order_id.partner_id.lang).code,
            partner=self.order_id.partner_id,
            quantity=vals.get('product_uom_qty') or self.product_uom_qty,
            date=self.order_id.date_order,
            pricelist=self.order_id.pricelist_id.id,
            uom=self.product_uom.id
        )

        vals.update(name=self.get_sale_order_line_multiline_description_sale(product))

        self._compute_tax_id()


        if self.get_the_price():
            vals['price_unit']=self.get_the_price()


        # if self.order_id.pricelist_id and self.order_id.partner_id:
        #     vals['price_unit'] = self.env['account.tax']._fix_tax_included_price_company(
        #         self._get_display_price(product), product.taxes_id, self.tax_id, self.company_id)
        self.update(vals)

        title = False
        message = False
        result = {}
        warning = {}
        if product.sale_line_warn != 'no-message':
            title = _("Warning for %s") % product.name
            message = product.sale_line_warn_msg
            warning['title'] = title
            warning['message'] = message
            result = {'warning': warning}
            if product.sale_line_warn == 'block':
                self.product_id = False

        return result

    def _compute_tax_id(self):
        for line in self:
            # If company_id is set, always filter taxes by the company
            line.tax_id = self.order_id.partner_id.tax_id

    @api.onchange('product_uom', 'product_uom_qty')
    def product_uom_change(self):
        return
        if not self.product_uom or not self.product_id:
            self.price_unit = 0.0
            return
        if self.order_id.pricelist_id and self.order_id.partner_id:
            product = self.product_id.with_context(
                lang=self.order_id.partner_id.lang,
                partner=self.order_id.partner_id,
                quantity=self.product_uom_qty,
                date=self.order_id.date_order,
                pricelist=self.order_id.pricelist_id.id,
                uom=self.product_uom.id,
                fiscal_position=self.env.context.get('fiscal_position')
            )
            self.price_unit = self.env['account.tax']._fix_tax_included_price_company(self._get_display_price(product), product.taxes_id, self.tax_id, self.company_id)






